<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>信号交叉口配时参数计算</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
        }
        body {
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
            padding: 20px;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            color: #2c3e50;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #eee;
        }
        h2 {
            color: #3498db;
            margin: 20px 0 15px;
        }
        .form-group {
            margin-bottom: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #2c3e50;
        }
        select, input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            margin-bottom: 10px;
        }
        button {
            background: #3498db;
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            display: block;
            width: 100%;
            margin-top: 15px;
            transition: background 0.3s;
        }
        button:hover {
            background: #2980b9;
        }
        .phase-inputs {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }
        .result-section {
            margin-top: 30px;
            padding: 20px;
            background: #e8f4fc;
            border-radius: 8px;
        }
        .result-item {
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px dashed #ccc;
        }
        .result-title {
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 5px;
        }
        .phase-results {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 10px;
        }
        .phase-result {
            background: #d1ecf1;
            padding: 10px;
            border-radius: 5px;
        }
        .error {
            color: #e74c3c;
            font-weight: bold;
            margin-top: 10px;
        }
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        .modal-content {
            background-color: white;
            padding: 25px;
            border-radius: 10px;
            max-width: 800px;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
            position: relative;
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        .modal-title {
            font-size: 24px;
            color: #2c3e50;
        }
        .close-btn {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #7f8c8d;
            position: absolute;
            top: 15px;
            right: 15px;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: all 0.3s;
        }
        .close-btn:hover {
            background-color: #f0f0f0;
            color: #333;
        }
        .formula-item {
            margin-bottom: 15px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
        }
        .formula-title {
            font-weight: bold;
            margin-bottom: 8px;
            color: #2c3e50;
        }
        .formula-content {
            font-family: monospace;
            white-space: pre-wrap;
            background: #f1f1f1;
            padding: 10px;
            border-radius: 4px;
            overflow-x: auto;
        }
        .phase-name-input {
            margin-bottom: 10px;
        }
        .help-btn {
            background: #2ecc71;
            width: auto;
            display: inline-block;
            padding: 8px 15px;
            margin-top: 0;
            margin-bottom: 20px;
        }
        @media (max-width: 768px) {
            .phase-inputs, .phase-results {
                grid-template-columns: 1fr;
            }
            .modal-content {
                width: 90%;
                padding: 15px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>信号配时参数计算器</h1>
        
        <button id="helpBtn" class="help-btn">查看计算公式说明</button>
        
        <div class="form-group">
            <label for="phaseScheme">选择信号相位方案：</label>
            <select id="phaseScheme">
                <option value="2">两相位方案</option>
                <option value="3">三相位方案</option>
                <option value="4">四相位方案</option>
            </select>
        </div>

        <div class="form-group">
            <h2>输入各相位参数</h2>
            <div class="phase-inputs" id="phaseInputs">
                <!-- 动态生成的输入字段将在这里显示 -->
            </div>
        </div>

        <button id="calculateBtn">计算信号配时参数</button>

        <div class="result-section" id="results" style="display: none;">
            <h2>计算结果</h2>
            
            <div class="result-item">
                <div class="result-title">信号总损失时间 (L):</div>
                <div id="totalLossTime"></div>
            </div>
            
            <div class="result-item">
                <div class="result-title">关键流率比之和 (Y):</div>
                <div id="sumFlowRatio"></div>
            </div>
            
            <div class="result-item">
                <div class="result-title">信号周期时长 (C):</div>
                <div id="signalCycle"></div>
            </div>
            
            <div class="result-item">
                <div class="result-title">总有效绿灯时间 (Ge):</div>
                <div id="totalGreenTime"></div>
            </div>
            
            <div class="result-item">
                <div class="result-title">各相位有效绿灯时间 (gej):</div>
                <div class="phase-results" id="phaseGreenTimes"></div>
            </div>
            
            <div class="result-item">
                <div class="result-title">各相位绿信比 (λ):</div>
                <div class="phase-results" id="greenRatios"></div>
            </div>
            
            <div class="result-item">
                <div class="result-title">各相位显示绿灯时间 (gj):</div>
                <div class="phase-results" id="displayGreenTimes"></div>
            </div>
        </div>

        <div id="errorMsg" class="error" style="display: none;"></div>
    </div>

    <!-- 公式说明模态框 -->
    <div id="formulaModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">信号配时计算公式说明</h2>
                <button class="close-btn">&times;</button>
            </div>
            
            <div class="formula-item">
                <div class="formula-title">1. 信号总损失时间 (L)</div>
                <div class="formula-content">L = ∑(L_s + I - A)_k
其中：
  L_s - 起动损失时间（本设计取3s）
  I - 绿灯间隔时间（本设计取6s）
  A - 黄灯时长（本设计取3s）
  k - 一个周期内的绿灯间隔数（等于相位数）

简化公式：L = 6 × 相位数</div>
            </div>
            
            <div class="formula-item">
                <div class="formula-title">2. 关键流率比之和 (Y)</div>
                <div class="formula-content">Y = ∑ max(y_j, y_j', ...)
其中：
  y_j - 第j相的流量比
  max(y_j, y_j', ...) - 第j相中流率比最大的车道组的流率比</div>
            </div>
            
            <div class="formula-item">
                <div class="formula-title">3. 信号周期时长 (C)</div>
                <div class="formula-content">C = L / (1 - Y / (PHF × (v/c)))
其中：
  PHF - 高峰小时系数（本设计取0.9）
  v/c - 交叉口设计饱和度（本设计取0.9）

注意：计算得到的信号周期不足40s时，取40s</div>
            </div>
            
            <div class="formula-item">
                <div class="formula-title">4. 总有效绿灯时间 (Ge)</div>
                <div class="formula-content">Ge = C - L</div>
            </div>
            
            <div class="formula-item">
                <div class="formula-title">5. 各相位有效绿灯时间 (gej)</div>
                <div class="formula-content">gej = Ge × (max(y_j, y_j', ...) / Y)</div>
            </div>
            
            <div class="formula-item">
                <div class="formula-title">6. 绿信比 (λ)</div>
                <div class="formula-content">λ = gej / C</div>
            </div>
            
            <div class="formula-item">
                <div class="formula-title">7. 显示绿灯时间 (gj)</div>
                <div class="formula-content">gj = gej - A_j + l_j
其中：
  l_j - 第j相位起动损失时间（本设计取3s）
  A_j - 第j相位的调整因子（本设计取3s）

简化公式：gj = gej</div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const phaseSchemeSelect = document.getElementById('phaseScheme');
            const phaseInputsDiv = document.getElementById('phaseInputs');
            const calculateBtn = document.getElementById('calculateBtn');
            const resultsDiv = document.getElementById('results');
            const errorMsgDiv = document.getElementById('errorMsg');
            const helpBtn = document.getElementById('helpBtn');
            const formulaModal = document.getElementById('formulaModal');
            const closeBtns = document.querySelectorAll('.close-btn');
            
            // 相位方案标签
            const defaultPhaseLabels = {
                2: ['南北直、左', '东西直、左'],
                3: ['南北左', '南北直、左', '东西直、左'],
                4: ['南北左', '南北直、左', '东西左', '东西直、左']
            };
            
            // 初始化输入字段
            updatePhaseInputs();
            
            // 当相位方案改变时更新输入字段
            phaseSchemeSelect.addEventListener('change', updatePhaseInputs);
            
            // 计算按钮点击事件
            calculateBtn.addEventListener('click', calculateResults);
            
            // 说明按钮点击事件
            helpBtn.addEventListener('click', function() {
                formulaModal.style.display = 'flex';
            });
            
            // 关闭模态框
            closeBtns.forEach(btn => {
                btn.addEventListener('click', function() {
                    formulaModal.style.display = 'none';
                });
            });
            
            // 点击模态框外部关闭
            window.addEventListener('click', function(event) {
                if (event.target === formulaModal) {
                    formulaModal.style.display = 'none';
                }
            });
            
            // 更新相位输入字段
            function updatePhaseInputs() {
                const scheme = phaseSchemeSelect.value;
                const labels = defaultPhaseLabels[scheme];
                
                phaseInputsDiv.innerHTML = '';
                
                labels.forEach((label, index) => {
                    const inputDiv = document.createElement('div');
                    inputDiv.innerHTML = `
                        <div class="phase-name-input">
                            <label for="phaseName${index}">相位 ${index+1} 名称（可选）:</label>
                            <input type="text" id="phaseName${index}" placeholder="${label}">
                        </div>
                        <label for="phase${index}">关键流率比 (y):</label>
                        <input type="number" id="phase${index}" step="0.001" min="0.001" max="1" value="0.1">
                    `;
                    phaseInputsDiv.appendChild(inputDiv);
                });
            }
            
            // 计算结果显示
            function calculateResults() {
                // 隐藏错误信息，显示结果区域
                errorMsgDiv.style.display = 'none';
                resultsDiv.style.display = 'block';
                
                // 移除已存在的按钮容器（如果有）
                const existingContainer = document.getElementById('customToolContainer');
                if (existingContainer) {
                    existingContainer.remove();
                }
                
                const scheme = parseInt(phaseSchemeSelect.value);
                const defaultLabels = defaultPhaseLabels[scheme];
                
                // 获取输入的相位名称和关键流率比
                const phaseNames = [];
                const flowRatios = [];
                let isValid = true;
                
                for (let i = 0; i < defaultLabels.length; i++) {
                    const nameInput = document.getElementById(`phaseName${i}`);
                    const ratioInput = document.getElementById(`phase${i}`);
                    
                    // 获取相位名称，如果用户没有输入则使用默认名称
                    const name = nameInput.value.trim() || defaultLabels[i];
                    phaseNames.push(name);
                    
                    // 获取关键流率比
                    const value = parseFloat(ratioInput.value);
                    
                    if (isNaN(value) || value <= 0 || value > 1) {
                        isValid = false;
                        showError('请输入有效的关键流率比 (0 < y ≤ 1)');
                        break;
                    }
                    
                    flowRatios.push(value);
                }
                
                if (!isValid) return;
                
                // 计算总损失时间 (L = 6 * 相位数)
                const totalLossTime = 6 * scheme;
                
                // 计算关键流率比之和 (Y)
                const sumFlowRatio = flowRatios.reduce((sum, ratio) => sum + ratio, 0);
                
                // 检查Y值是否合理
                if (sumFlowRatio > 0.9) {
                    showError('关键流率比之和Y值大于0.9，须改进进口道设计或信号相位方案');
                    return;
                }
                
                // 计算信号周期 (C = L / (1 - Y/(PHF*(v/c))))
                const PHF = 0.9;
                const vc = 0.9;
                let signalCycle = totalLossTime / (1 - sumFlowRatio / (PHF * vc));
                
                // 信号周期不足40s取40s
                if (signalCycle < 40) {
                    signalCycle = 40;
                }
                
                // 计算总有效绿灯时间 (Ge = C - L)
                const totalGreenTime = signalCycle - totalLossTime;
                
                // 计算各相位有效绿灯时间 (gej = Ge * (yj/Y))
                const phaseGreenTimes = flowRatios.map(ratio => 
                    (totalGreenTime * ratio / sumFlowRatio).toFixed(2)
                );
                
                // 计算各相位绿信比 (λ = gej / C)
                const greenRatios = phaseGreenTimes.map(time => 
                    (time / signalCycle).toFixed(4)
                );
                
                // 计算各相位显示绿灯时间 (gj = gej)
                const displayGreenTimes = [...phaseGreenTimes];
                
                // 显示计算结果
                document.getElementById('totalLossTime').textContent = `${totalLossTime} s`;
                document.getElementById('sumFlowRatio').textContent = sumFlowRatio.toFixed(6);
                document.getElementById('signalCycle').textContent = `${signalCycle.toFixed(2)} s`;
                document.getElementById('totalGreenTime').textContent = `${totalGreenTime.toFixed(2)} s`;
                
                // 显示各相位结果
                const phaseGreenTimesDiv = document.getElementById('phaseGreenTimes');
                const greenRatiosDiv = document.getElementById('greenRatios');
                const displayGreenTimesDiv = document.getElementById('displayGreenTimes');
                
                phaseGreenTimesDiv.innerHTML = '';
                greenRatiosDiv.innerHTML = '';
                displayGreenTimesDiv.innerHTML = '';
                
                phaseNames.forEach((name, index) => {
                    phaseGreenTimesDiv.innerHTML += `
                        <div class="phase-result">
                            <div>${name}:</div>
                            <div>${phaseGreenTimes[index]} s</div>
                        </div>
                    `;
                    
                    greenRatiosDiv.innerHTML += `
                        <div class="phase-result">
                            <div>${name}:</div>
                            <div>${greenRatios[index]}</div>
                        </div>
                    `;
                    
                    displayGreenTimesDiv.innerHTML += `
                        <div class="phase-result">
                            <div>${name}:</div>
                            <div>${displayGreenTimes[index]} s</div>
                        </div>
                    `;
                });
                
                // 在显示绿灯时间下方添加提示和按钮
                const customToolContainer = document.createElement('div');
                customToolContainer.id = 'customToolContainer'; // 添加唯一ID以便后续移除
                customToolContainer.style.marginTop = '20px';
                customToolContainer.style.padding = '15px';
                customToolContainer.style.backgroundColor = '#f8f9fa';
                customToolContainer.style.borderRadius = '8px';
                customToolContainer.innerHTML = `
                    <div style="margin-bottom: 10px; color: #2c3e50;">通用信号配时计算器的自定义相位时间功能可生成信号配时图！</div>
                    <button id="customTimingBtn" style="background: #9b59b6; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; font-size: 16px;">
                        通用配时计算器
                    </button>
                `;
                
                // 将容器添加到结果区域中的显示绿灯时间部分后面
                displayGreenTimesDiv.parentNode.appendChild(customToolContainer);
                
                // 添加按钮点击事件
                document.getElementById('customTimingBtn').addEventListener('click', function() {
                    window.location.href = './crossing.html';
                });
            }
            
            // 显示错误信息
            function showError(message) {
                errorMsgDiv.textContent = message;
                errorMsgDiv.style.display = 'block';
                resultsDiv.style.display = 'none';
            }
        });
    </script>
    <!-- 底部版权信息和博客链接 -->
    <footer style="text-align: center; margin-top: 40px; padding: 20px; background-color: #f8f9fa; border-radius: 8px;">
        <p>&copy; 2025 Luwei - 版权所有</p>
        <p><a href="https://sufine.top" target="_blank" style="color: #3498db; text-decoration: none;">Suffine Hub</a></p>
    </footer>
</body>
</html>